<template>
  <div class="default-org-wrapper">
    <p class="title">综合条件查询</p>
    <div class="form-search-area">
      <el-form :inline="true" :model="formInline" size="medium" class="demo-form-inline">
        <el-form-item label="机构名称">
          <el-input v-model="formInline.organNameLike" placeholder="请输入机构名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="formInline.organType" placeholder="请选择类型" clearable>
            <el-option
             v-for="(item) in DICY.orgType"
             :key="item.code"
             :label="item.name"
             :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="层级">
          <el-select v-model="formInline.organLevel" placeholder="请选择层级" clearable>
            <el-option
             v-for="(item) in DICY.orgLevel"
             :key="item.code"
             :label="item.name"
             :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="medium" @click="searchOrg">查询</el-button>
          <el-button size="medium" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="right-btn-area">
        <el-button size="medium" type="primary" @click="popNewAddDialog">新增机构</el-button>
        <el-button size="medium">导入</el-button>
        <el-button size="medium" @click="exportTable">导出</el-button>
        <el-button size="medium" @click="batchDeletion">批量删除</el-button>
      </div>
    </div>
    <!-- 表格 开始-->
    <div class="table-area clearfix">
      <el-table :data="tableData" ref="multipleTable" @selection-change="selectionChange" v-loading="loading" stripe>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" width="50">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="机构名称" prop="organName"></el-table-column>
        <el-table-column label="机构类型" prop="organType">
          <template slot-scope="scope">{{convertKeyToVal (scope.row.organType, DICY.orgType)}}</template>
        </el-table-column>
        <el-table-column label="机构层级" prop="organLevel" show-overflow-tooltip>
          <template slot-scope="scope">{{convertKeyToVal (scope.row.organLevel, DICY.orgLevel)}}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" icon="el-icon-view" @click="viewDetail(scope.row.id)">查看</el-link>
            <el-link type="success" :underline="false" icon="el-icon-edit" @click="editDetail(scope.row.id)">编辑</el-link>
            <el-link type="danger" :underline="false" icon="el-icon-delete" @click="deleteDetail(scope.row.id)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="paging-self"
        background
        :current-page.sync="currentPage"
        @current-change="pageChange"
        layout="total, prev, pager, next"
        :total="totalCount">
      </el-pagination>
    </div>
    <!-- 表格 结束-->
    <!-- 对话框 开始 -->
    <el-dialog title="综治机构" :visible.sync="dialogFormVisible" width="660px" @closed="closeDialog">
      <el-form :model="dialogForm" class="dialog-form-comot" :disabled="dialogMode===CNST.READ_MODE" :rules="rules" ref="ruleDialog">
        <el-form-item label="机构名称" label-width="100px" prop="organName">
          <el-input v-model="dialogForm.organName" placeholder="请输入机构名称" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属辖区" label-width="100px">
          <el-cascader
            v-model="dialogForm.region"
            :options="options"
            @change="handleChange"
            placeholder="请选择所属辖区">
          </el-cascader>
        </el-form-item>
        <el-form-item label="机构类型" label-width="100px" prop="organType">
          <el-select v-model="dialogForm.organType" placeholder="请选择机构类型">
            <el-option
             v-for="(item) in DICY.orgType"
             :key="item.code"
             :label="item.name"
             :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机构层级" label-width="100px" prop="organLevel">
          <el-select v-model="dialogForm.organLevel" placeholder="请选择机构层级">
            <el-option
             v-for="(item) in DICY.orgLevel"
             :key="item.code"
             :label="item.name"
             :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOrg" v-if="dialogMode!==CNST.READ_MODE">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 对话框 结束 -->
  </div>
</template>

<script>
import { getGovernOrganList, addGovernOrgan, getGovernOrganDetail, updateGovernOrganDetail, deleteGovernOrganItem, deleteGovernOrganBatch, exportGovernOrgan } from '@/api/baseBusiness'
import { deepClone, parseTime } from '@/utils'
import { mapState } from 'vuex'

export default {
  name: 'DefaultOrg',
  data () {
    return {
      formInline: {
        organNameLike: '',
        organType: '',
        organLevel: ''
      },
      // table property
      loading: false,
      tableData: [],
      multipleSelection: [],
      // dialog property
      dialogFormVisible: false,
      dialogForm: {
        organName: '',
        organType: '',
        organLevel: '',
        organDesc: ''
      },
      // 级联
      options: this.DICY.jilian,
      dialogMode: '', // 对话框的状态，新增，查看，编辑
      curId: '', // 点击查看或编辑的当前列表项的id
      totalCount: 0, // 总共多少条
      currentPage: 1, // 分页当前页
      rules: {
        organName: [
          { required: true, message: '请输入机构名称', trigger: 'blur' },
          { max: 100, message: '长度在 50 个汉字以内', trigger: 'blur' }
        ],
        organType: [
          { required: true, message: '请选择机构类型', trigger: 'change' }
        ],
        organLevel: [
          { required: true, message: '请选择机构层级', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    ...mapState([
      'areaId'
    ])
  },
  methods: {
    convertKeyToVal (code, arr) {
      arr = Array.isArray(arr) ? arr : []
      let resArr = arr.filter((item) => {
        return item.code === code
      })
      if (resArr.length === 0) {
        return ''
      }
      return resArr[0].name
    },
    searchOrg () {
      this.currentPage = 1
      this.getOrgListAndShow()
    },
    resetSearch () {
      for (let key in this.formInline) {
        this.$set(this.formInline, key, '')
      }
      this.currentPage = 1
      this.getOrgListAndShow()
    },
    selectionChange (valArr) {
      this.multipleSelection = valArr
    },
    pageChange (curPage) {
      this.currentPage = curPage
      this.getOrgListAndShow()
    },
    popNewAddDialog () {
      this.dialogFormVisible = true
      this.dialogMode = this.CNST.ADDNEW_MODE
    },
    // 新增或修改机构
    submitOrg () {
      this.$refs.ruleDialog.validate((valid) => {
        if (valid) {
          // -----------------
          let requestData = deepClone(this.dialogForm)
          if (this.dialogMode === this.CNST.ADDNEW_MODE) {
            // 新增
            requestData.areaId = this.areaId
            addGovernOrgan(requestData).then((res) => {
              this.$message({
                message: '新增机构成功',
                type: 'success'
              })
              this.getOrgListAndShow()
              this.dialogFormVisible = false
            })
          } else if (this.dialogMode === this.CNST.EDIT_MODE) {
            // 修改
            requestData.id = this.curId
            updateGovernOrganDetail(requestData).then((res) => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.getOrgListAndShow()
              this.dialogFormVisible = false
            })
          }
          // -----------------
        } else {
          return false
        }
      })
    },
    handleChange (value) {
      console.log(value)
    },
    async getOrgListAndShow () {
      try {
        this.loading = true
        let requestData = {
          page: this.currentPage,
          areaId: this.areaId,
          ...deepClone(this.formInline)
        }
        var res = await getGovernOrganList(requestData)
        this.tableData = res.data.queryResult
        this.totalCount = res.data.totalCount
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    showToDialog (data) {
      for (let key in data) {
        if (this.dialogForm.hasOwnProperty(key)) {
          this.dialogForm[key] = data[key]
        }
      }
    },
    viewDetail (id) {
      this.dialogMode = this.CNST.READ_MODE
      this.dialogFormVisible = true
      getGovernOrganDetail({ id }).then((res) => {
        this.showToDialog(res.data)
      })
    },
    editDetail (id) {
      this.dialogMode = this.CNST.EDIT_MODE
      this.dialogFormVisible = true
      this.curId = id
      getGovernOrganDetail({ id }).then((res) => {
        this.showToDialog(res.data)
      })
    },
    deleteDetail (id) {
      this.$confirm('确定删除, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        deleteGovernOrganItem({ id }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getOrgListAndShow()
        })
      })
    },
    batchDeletion () {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请勾选要删除的项!'
        })
      } else {
        var ids = this.multipleSelection.map((item) => {
          return item.id
        }).join(',')
        this.$confirm('确定删除, 是否继续?', '批量删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteGovernOrganBatch({ ids }).then((res) => {
            this.$message({
              type: 'success',
              message: '批量删除成功!'
            })
            this.getOrgListAndShow()
          })
        })
      }
    },
    closeDialog () {
      // 当前点击查看或编辑列表项的id置空
      this.curId = ''
      // 弹框关闭后重置表单验证
      this.$refs.ruleDialog.resetFields()
      // 清空弹框内表单数据
      for (let key in this.dialogForm) {
        this.dialogForm[key] = ''
      }
    },
    exportTable () {
      exportGovernOrgan({
        areaId: this.areaId,
        options: 'organName,region,organType,organLevel',
        titles: '机构名称,所属辖区,机构类型,机构层级'
      }).then((res) => {
        console.log(res)
        var blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        var objectUrl = URL.createObjectURL(blob)
        var a = document.createElement('a')
        document.body.appendChild(a)
        a.style = 'display: none'
        a.href = objectUrl
        a.download = '综治机构' + parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(objectUrl)
        this.$message({
          message: '导出成功',
          type: 'success'
        })
      })
    }
  },
  mounted () {
    this.getOrgListAndShow()
  }
}
</script>

<style lang="scss" scoped>
.default-org-wrapper {
  background-color: #ffffff;
  margin-top: 12px;
  border-radius: 4px;
  box-shadow: 10px 10px 22px -2px #d2d6da;
  padding: 20px;
  .title {
    margin: 0;
    font-size: 15px;
    color: #333333;
    margin-bottom: 10px;
  }
  .form-search-area {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }
  .table-area {
    .el-link {
      margin-right: 13px;
    }
    .el-pagination.paging-self {
      margin-top: 20px;
      float: right;
    }
  }
  .el-form.dialog-form-comot {
    .el-form-item {
      .el-cascader,.el-select {
        width: 100%;
      }
    }
  }
}
</style>
